<template>
  <div class="comment">
    <h3>发表评论</h3>
    <hr>
    <textarea placeholder="请输入要BB的内容（最多吐槽120字）" maxlength="120" v-model="msg"></textarea>
    <van-button type="danger" size="large" @click="postcomment">发表评论</van-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,index) in comments" :key="index">
        <div
          class="cmt-title"
        >第{{index+1}}楼&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间：{{item.add_time | datefmt}}</div>
        <div class="cmt-body">{{ item.content === 'undefined' ? '此用户很懒，嘛都没说': item.content }}</div>
      </div>
    </div>
    <van-button type="danger" size="large" @click="getMore" plain>{{hasFlag?'没有更多数据':'加载更多'}}</van-button>
  </div>
</template>
<script>
import { Toast } from "vant";
export default {
  data: () => ({
    pageindex: 0,
    limit: 6,
    comments: [],
    msg: "",
    hasFlag: false
  }),
  props: ["id"],
  created() {
    this.getcomments();
  },
  methods: {
    async getcomments() {
      if (this.hasFlag) return;
      this.pageindex++;
      const {
        data: { status, message, count }
      } = await this.$http.get(
        `api/getcomments/${this.id}?pageindex=${this.pageindex}&limit=${
          this.limit
        }`
      );
      if (status === 0) {
        // 把第一页的数据和下一页拼接成一个新的数组
        this.comments = this.comments.concat(message);
        this.hasFlag = this.pageindex * this.limit > count;
      } else {
        Toast("获取评论信息失败");
      }
    },
    getMore() {
      this.getcomments();
    },
    async postcomment() {
      if (this.msg.length === 0) {
        Toast("数据不能为空");
        return;
      }
      const {
        data: { status, message }
      } = await this.$http.post(`api/postcomment/${this.id}`, {
        content: this.msg
      });
      if (status === 0) {
        // 1. 拼接出一个评论对象
        var cmt = {
          user_name: "匿名用户",
          content: this.msg.trim()
        };
        // 添加到数组的开头 重新修改  comments 使得  model 改变  v-for 自动就刷新数据
        this.comments.unshift(cmt);
        // 清空
        this.msg = "";
      } else {
        Toast("评论失败");
      }
    }
  }
};
</script>
<style lang="less">
.comment {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    width: 100%;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>